﻿namespace ContactsSync.Infrastructure
{
    using System;
    using System.Xml.Linq;

    public static class XmlExtensions
    {
        public static string GetValue(this XElement element)
        {
            if (element != null)
            {
                return element.Value;
            }

            return null;
        }

        public static string GetValue(this XAttribute attribute)
        {
            if (attribute != null)
            {
                return attribute.Value;
            }

            return null;
        }

        public static long? GetValueAsLong(this XAttribute attribute)
        {
            long result;

            if (attribute != null && long.TryParse(attribute.GetValue(), out result))
            {
                return result;
            }

            return null;
        }

        public static double? GetValueAsDouble(this XAttribute attribute)
        {
            double result;

            if (attribute != null && double.TryParse(attribute.GetValue(), out result))
            {
                return result;
            }

            return null;
        }

        public static Guid GetValueAsGuid(this XAttribute attribute)
        {
            try
            {
                return new Guid(attribute.GetValue());
            }
            catch
            {
                return Guid.Empty;
            }
        }

        public static Guid GetValueAsGuid(this XElement element)
        {
            try
            {
                return new Guid(element.GetValue());
            }
            catch
            {
                return Guid.Empty;
            }
        }

        public static double? GetValueAsDouble(this XElement element)
        {
            double result;

            if (element != null && double.TryParse(element.GetValue(), out result))
            {
                return result;
            }

            return null;
        }

        public static int? GetValueAsInt(this XElement element)
        {
            int result;

            if (element != null && int.TryParse(element.GetValue(), out result))
            {
                return result;
            }

            return null;
        }

        public static Uri GetValueAsUri(this XElement element)
        {
            return element.GetValueAsUri(UriKind.RelativeOrAbsolute);
        }

        public static Uri GetValueAsUri(this XElement element, UriKind uriKind)
        {
            Uri uri;

            if (element != null && Uri.TryCreate(element.GetValue(), uriKind, out uri))
            {
                return uri;
            }

            return null;
        }
    }
}
